﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Billing.DataObjects;

namespace Billing.Win
{
    public partial class TablesEditorForm : Billing.WindowsBase.FormBase
    {
        BillingDataContext mBillingDataContext = new BillingDataContext();
        bool mAllowSubmit;

        [RightAttributeExistence("AllowSubmit")]
        public bool AllowSubmit
        {
            get { return mAllowSubmit; }
            set
            {
                mAllowSubmit = value;
                btnSave.Visible = mAllowSubmit;
            }
        }

        public TablesEditorForm()
        {
            InitializeComponent();
            listBox.DataSource = mBillingDataContext.TablesLists;
        }

        private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox.SelectedValue != null)
            {
                try
                {
                    System.Data.Linq.ITable table = mBillingDataContext.GetTable(Type.GetType(Convert.ToString(listBox.SelectedValue)));
                    grd.DataSource = table;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                grd.DataSource = null;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            mBillingDataContext.SubmitChanges();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (mAllowSubmit && (mBillingDataContext.GetChangeSet().Deletes.Count > 0
                || mBillingDataContext.GetChangeSet().Updates.Count > 0
                || mBillingDataContext.GetChangeSet().Inserts.Count > 0))
            {
                if (MessageBox.Show("შევინახო შეცვლილი მონაცემები?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    mBillingDataContext.SubmitChanges();
            }
            Close();

        }
    }
}
